package com.example.kcp.net;

import com.example.kcp.utils.BytesUtil;
import io.netty.handler.logging.ByteBufFormat;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramPacket;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @author "陈凯航"
 * @date 2024/10/8
 * @mail "mengxingcn@aliyun.com"
 */
@RequiredArgsConstructor
@Component
public class UdpServer implements CommandLineRunner {

    private final Vertx vertx;

    @Override
    public void run(String... args) throws Exception {

        DatagramSocketOptions options = new DatagramSocketOptions();
        options.setLogActivity(true);
        options.setActivityLogDataFormat(ByteBufFormat.HEX_DUMP);
        DatagramSocket datagramSocket = vertx.createDatagramSocket(options);
        datagramSocket.listen(1234, "0.0.0.0");
        datagramSocket.handler(new Handler<DatagramPacket>() {
            @Override
            public void handle(DatagramPacket event) {
                byte[] bytes = event.data().getBytes();
                String s = BytesUtil.bytesToHex(bytes);
                System.out.println("s = " + s);
            }
        });
    }
}
